package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.data.Result;
import com.dongdongshop.pojo.admin.TbUser;
import com.dongdongshop.pojo.seckill_goods.TbSeckillGoods;
import com.dongdongshop.service.seckill_goods.SeckillGoodsService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("seckill")
public class SeckillController {
    @Reference
    private SeckillGoodsService seckillGoodsService;
    private Logger logger = LoggerFactory.getLogger(SeckillController.class);

    @RequestMapping("seckillShow")
    public String seckillShow(){
        return "seckill-index";
    }
    @RequestMapping("listSeckillItems")
    @ResponseBody
    public Result listSeckillItems(){
        try {
            List<TbSeckillGoods> seckillGoodsList = seckillGoodsService.listSeckillItems();
            return Result.ok().setData(seckillGoodsList);
        }catch (Exception e){
            logger.error("查询错误",e);
            return Result.fail();
        }
    }
    @RequestMapping("seckillItemShow")
    public String  seckillItemShow(Long id, Model model){
            TbSeckillGoods tbSeckillGoods = seckillGoodsService.getSeckillItem(id);
            model.addAttribute("good",tbSeckillGoods);
            return "seckill-item";
    }
    @RequestMapping("updateStockCount")
    @ResponseBody
    public Result updateStockCount(Long id){
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (null == user){
            return Result.unatuth();
        }
        try {
            seckillGoodsService.updateStockCount(id,user.getUsername());
        }catch (Exception e){
            logger.error("秒杀异常",e);
            return Result.fail();
        }
        return Result.ok();
    }
}
